/*
 *   Copyright 2008 Francois Fernandes
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.googlecode.opendoclibrary.connector.internal;

import java.io.InputStream;

import com.googlecode.opendoclibrary.IDocumentConsumer;
import com.googlecode.opendoclibrary.ILibraryConnection;
import com.googlecode.opendoclibrary.IStorageRequest;
import com.googlecode.opendoclibrary.StorageException;
import com.googlecode.opendoclibrary.connector.spi.IConnection;

public class VMLibraryConnection implements ILibraryConnection
{
    private final String libraryName;

    private final IConnection target;

    public VMLibraryConnection( String libraryName, IConnection target )
    {
        this.libraryName = libraryName;
        this.target = target;
    }

    @Override
    public IStorageRequest createStorageRequest()
    {
        return target.createStorageRequest( libraryName );
    }

    @Override
    public void retrieveDocument( String documentId, IDocumentConsumer consumer ) throws StorageException
    {
        InputStream in = target.getDocumentData( libraryName, documentId );
        if ( in == null )
        {
            try
            {
                consumer.failed( documentId, "no document with id: " + documentId );
            }
            catch ( Throwable t )
            {
                log.error( "consumer.failed invocation failed.", t );
            }
        }
        else
        {
            // found the document data
            try
            {
                consumer.consume( documentId, in );
            }
            catch ( Throwable t )
            {
                log.error( "consumer.consume invocation failed.", t );
            }
        }
    }
}
